package com.tweetwhore.domain;

import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Scanner;

import javax.swing.JOptionPane;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class Client {

	public static void main(String args[]) throws Exception {
		// The factory instance is re-usable and thread safe.
		Twitter twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer("rN4DKlPt66dUjHQDY8v75w",
				"KslsVe4FJHToaFMdX7PW77m3rJz3hGkkZf3QxIsy55I");
		RequestToken requestToken = twitter.getOAuthRequestToken();
		AccessToken accessToken = null;
		while (null == accessToken) {
			String authorizationUrl = requestToken.getAuthorizationURL();
			java.awt.Desktop.getDesktop().browse(java.net.URI.create(authorizationUrl));
			String pin = JOptionPane
					.showInputDialog("Enter the PIN (if available) or just hit enter: ");
			try {
				if (pin.length() > 0) {
					accessToken = twitter
							.getOAuthAccessToken(requestToken, pin);
				} else {
					accessToken = twitter.getOAuthAccessToken();
				}
			} catch (TwitterException twitterException) {
				if (401 == twitterException.getStatusCode()) {
					JOptionPane.showMessageDialog(null,
							"Unable to get the access token.", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					twitterException.printStackTrace();
				}
			}
		}

		// persist to the accessToken for future reference.
		// storeAccessToken(twitter.verifyCredentials().getId() , accessToken);
		
		// Write credentials to a file
		
		Scanner readFile = new Scanner(new FileReader("data.dat"));
		String dataContents = "";
		while(readFile.hasNext()) {
			dataContents += readFile.nextLine();
		}
		
		PrintWriter storageFile = new PrintWriter("data.dat");
		storageFile.write("\n" + dataContents + "\n" + twitter.verifyCredentials().getScreenName() + " " + accessToken.getToken() + " " + accessToken.getTokenSecret());
		storageFile.close();
		
		
		Status status = null;
		String tweet = JOptionPane.showInputDialog("Post a new tweet: ");
		try {
			status = twitter.updateStatus(tweet);
		} catch (TwitterException twitterException) {
			JOptionPane.showMessageDialog(null,
					"Error posting your tweet. Please try again", "Error",
					JOptionPane.ERROR_MESSAGE);
		}
		JOptionPane.showMessageDialog(null,
				"Successfully posted a new tweet:\n\"" + status.getText()
						+ "\"", "Success", JOptionPane.INFORMATION_MESSAGE);
		System.exit(0);
	}

	private static void storeAccessToken(int useId, AccessToken accessToken) {
		// store accessToken.getToken()
		// store accessToken.getTokenSecret()
	}

}
